package com.yc.cloud.portal.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.cloud.common.basic.dto.BaseQueryParam;
import com.yc.cloud.common.basic.utils.RequestUtil;
import com.yc.cloud.entity.MemberLoginLog;
import com.yc.cloud.mapper.MemberLoginLogMapper;
import com.yc.cloud.portal.service.MemberLoginLogService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.val;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;



/**
 * <p>
 * 会员登录日志表 服务实现类
 * </p>
 *
 * @author Yancy
 * @since 2023-12-23
 */
@Service
public class MemberLoginLogServiceImpl extends ServiceImpl<MemberLoginLogMapper, MemberLoginLog> implements MemberLoginLogService {

    @Resource
    private MemberLoginLogMapper memberLoginLogMapper;

    @Override
    public IPage<MemberLoginLog> list(BaseQueryParam queryParam) {
        val query = new QueryWrapper<MemberLoginLog>();
        IPage<MemberLoginLog> page;
        //排序
        if (StrUtil.isNotEmpty(queryParam.getSortBy())) {
            if (BaseQueryParam.ORDER_DESC.equals(queryParam.getOrder())) {
                query.orderByDesc(MemberLoginLog.ID);
            } else if (BaseQueryParam.ORDER_ASC.equals(queryParam.getOrder())) {
                query.orderByAsc(MemberLoginLog.ID);
            }
        }
        //模糊查询
        if (StrUtil.isNotEmpty(queryParam.getKeyword())) {
            query.and(queryWrapper -> {

            });
        }
        //分页
        if (queryParam.getPage()) {
            page = new Page<>(queryParam.getPageNum(), queryParam.getPageSize(), true);
        } else {
            page = new Page<>(queryParam.getPageNum(), memberLoginLogMapper.selectCount(query), true);
        }
        return memberLoginLogMapper.selectPage(page, query);
    }

    @Override
    public void saveMemberLoginLog(Long memberId) {
        val memberLoginLog = new MemberLoginLog();
        memberLoginLog.setMemberId(memberId);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            HttpServletRequest request = attributes.getRequest();
            memberLoginLog.setIp(RequestUtil.getRequestIp(request));
        }
        baseMapper.insert(memberLoginLog);
    }
}
